﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using EasyIot.Model;
using EasyIot.Service;
using EasyIot.WebApp.Controllers;

namespace EasyIot.WebApp.Areas.Permissions.Controllers
{
    public class ItemsController : BaseController
    { 
        // GET: Permissions/Items
        public override ActionResult Index(int? id)
        {
            base.Index(id);
            return View();
        }

        [HttpGet]
        public JsonResult List()
        {
            var list = ItemsService.GetAll();
            var result = new { code = 0, count = list.Count(), data = list };
            return Json(result);
        }

        [HttpGet]
        public JsonResult GetItemsTreeSelect()
        {
            var result = ItemsService.GetItemsTreeSelect();
            return Json(result);
        }

        public ActionResult Add()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Add(ItemsModel model)
        {
            if (ItemsService.IsExistCode(model.EnCode))
            {
                return Json(ErrorTip("该编码已经存在!"));
            }

            model.CreateTime = DateTime.Now;
            model.CreateUserId = Operator.UserId;
            model.UpdateTime = DateTime.Now;
            model.UpdateUserId = Operator.UserId;
            var result = ItemsService.Insert(model) ? SuccessTip("添加成功") : ErrorTip("添加失败");
            return Json(result);
        }

        public ActionResult Edit(int id)
        {
            var model = ItemsService.GetById(id);
            model.EnCode_EditBefore = model.EnCode;
            return View(model);
        }

        [HttpPost]
        public ActionResult Edit(ItemsModel model)
        {
            if (!model.EnCode_EditBefore.Trim().ToLower().Equals(model.EnCode.Trim().ToLower()) && ItemsService.IsExistCode(model.EnCode))
            {
                return Json(ErrorTip("该编码已经存在!"));
            }

            model.UpdateTime = DateTime.Now;
            model.UpdateUserId = Operator.UserId;
            var result = ItemsService.UpdateById(model) ? SuccessTip("修改成功") : ErrorTip("修改失败");
            return Json(result);
        }

        [HttpGet]
        public JsonResult Delete(int id)
        {  
            var result = ItemsService.DeleteContactById(id) ? SuccessTip("删除成功") : ErrorTip("删除失败");
            return Json(result);
        } 
    }
}